package com.bjesc_b2c.app.appraiset.camera;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bjesc_b2c.app.appraiset.AppraiserApplication;
import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.base.BaseActivity;
import com.bjesc_b2c.app.appraiset.bean.TakePhotoBean;
import com.bjesc_b2c.app.appraiset.utils.TimeListUilts;
import com.bjesc_b2c.app.appraiset.widget.MySurfaceView;
import com.bjesc_b2c.app.appraiset.widget.view.FocusImageView;
import com.bjesc_b2c.app.appraiset.widget.view.RotateImageView;
import com.bjesc_b2c.app.appraiset.widget.view.ViewUtil;
import com.bumptech.glide.Glide;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.CarPhotoID;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnTouch;
import master_bean.CarSourcePhotoBean;

import static android.os.Build.VERSION_CODES.M;
import static com.bjesc_b2c.app.appraiset.R.id.sv_take_photo;

/**
 * 拍照页面
 * 
 * Created by up_girl on 2017/3/30.
 */
public class TakePhoto extends BaseActivity implements CameraInterface.CamOpenOverCallback, View.OnClickListener {
    private final int GET_PERMISSION_REQUEST = 100; //权限申请自定义码
    private boolean granted = false;
    private static final String TAG = "TakePhoto";
    public static File mTempFile;
    //旋转角度
    public static int rotate = 0;
    public static final int BACK_PHOTO_SUCCEED = 28;
    private final int WHAT_TAKE_PHOTO_SUCCEED = 0;
    public static String TEMP_PHONE_FILENAME = "";
    private RotateImageView image;
    private TextView textView;
    private MySurfaceView vSurfaceView;
    protected List<CarSourcePhotoBean> photoBeanList = new ArrayList<>();
    protected List<TakePhotoBean> photoList = new ArrayList<>();
    private int sourceID;
    private MyOrientationEventListener mOrientationListener;
    int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN;
    @InjectView(R.id.focusimageview)
    FocusImageView focusImageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.take_photo);
        ButterKnife.inject(this);
        setSurfaceView();
        loadPhotoNameList();
        mOrientationListener = new MyOrientationEventListener(this);
        findView();
        getPermissions();
    }
    Thread openThread = new Thread(){
        @Override
        public void run() {
            CameraInterface.getInstance().doOpenCamera(TakePhoto.this);
        }
    };
    private void setSurfaceView() {
        vSurfaceView = (MySurfaceView) findViewById(sv_take_photo);
        ViewGroup.LayoutParams params = vSurfaceView.getLayoutParams();
        params.width = DisplayUtil.getScreenWidth(this);
        params.height = DisplayUtil.getScreenHeight(this)*3/4;
        vSurfaceView.setLayoutParams(params);
    }
     private void loadPhotoNameList(){
         sourceID = getIntent().getIntExtra("currentIndex",0);
        String carPhotoId = getIntent().getStringExtra("CarPhotoID");
         if(!TextUtils.isEmpty(carPhotoId)){
             if (carPhotoId.equals(CarPhotoID.SURFACEID)){//外观
                 photoBeanList = TimeListUilts.getSurfacePhotoList();
             }else if(carPhotoId.equals(CarPhotoID.ORNAMENTSID)){//中控
                 photoBeanList = TimeListUilts.getOrnamentsPhotoList();
             }else if (carPhotoId.equals(CarPhotoID.ENGINEID)){//底盘
                 photoBeanList = TimeListUilts.getEnginePhotoList();
             }else if(carPhotoId.equals(CarPhotoID.PROCEDURESID)){//手续
                 photoBeanList = TimeListUilts.getProceduresPhotoList();
             }
         }
     }
    @OnTouch(R.id.sv_take_photo)
    public boolean take(View View, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_UP:
                Point point = new Point((int) event.getX(), (int) event.getY());
                CameraInterface.getInstance().onFocus(point);
                focusImageView.startFocus(point);
                break;
        }
        return true;
    }

    private void findView() {
        image = (RotateImageView )findViewById(R.id.image);
        textView = (TextView)findViewById(R.id.textView);
        FrameLayout rl = (FrameLayout) findViewById(R.id.rl_take_photo);
        RelativeLayout.LayoutParams rlPs = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        rlPs.width = DisplayUtil.getScreenWidth(this);
        rlPs.height = DisplayUtil.getScreenHeight(this);
        rl.setLayoutParams(rlPs);
        RelativeLayout llBottom = (RelativeLayout) findViewById(R.id.ll_take_photo);
        RelativeLayout.LayoutParams llPs = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        llPs.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        llPs.width = DisplayUtil.getScreenWidth(this);
        llPs.height = DisplayUtil.getScreenHeight(this) * 1 / 4;
        llBottom.setLayoutParams(llPs);
        ImageButton btnTakePhoto = (ImageButton) findViewById(R.id.btn_take_photo);
        btnTakePhoto.setOnClickListener(this);
        textView.setText(photoBeanList.get(sourceID).getPhotoName());
    }

    @Override
    public void cameraHasOpened() {
        SurfaceHolder holder = vSurfaceView.getSurfaceHolder();
        try {
            CameraInterface.getInstance().doStartPreview(TakePhoto.this,holder,
                    DisplayUtil.getScreenWidth(TakePhoto.this), DisplayUtil.getScreenHeight(TakePhoto.this)*3/4);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_take_photo:
                if (ImageUtil.hasSdcard()) {
//                    BitmapUtil.prepareFile(Environment.getExternalStorageDirectory() + "/DCIM/"); // 准备文件夹
                    String fileName = ImageUtil.getPhotoFileName();
//                    mTempFile = new File(Environment.getExternalStorageDirectory() + "/DCIM/", fileName);
                    TEMP_PHONE_FILENAME = fileName;
//                    CameraInterface.getInstance().mCamera.autoFocus(new Camera.AutoFocusCallback() {
//                        @Override
//                        public void onAutoFocus(boolean b, Camera camera) {
//                            if (b) {
//                                focusImageView.onFocusSuccess();
                                try {
                                    CameraInterface.getInstance().doTakePicture();
                                    Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/pinggushi/",
                                            TEMP_PHONE_FILENAME));
                                    Log.d(TAG, "Uri===" + String.valueOf(uri));
                                    Message msgObj = mHandler.obtainMessage(WHAT_TAKE_PHOTO_SUCCEED, uri);
                                    mHandler.sendMessageDelayed(msgObj, 1500);
                                } catch (Exception e) {
                                    showToast( "您的照相机没有正常打开，请重新试一试哟");
                                    Log.e(TAG, e + "");
                                }
//                            } else {
//                                focusImageView.onFocusFailed();
//                            }
//                        }
//                    });

                } else {
                    showToast("没找到您的SD卡");
                }
                break;
            default:
                break;
        }
    }
    private class MyOrientationEventListener extends OrientationEventListener{

        public MyOrientationEventListener(Context context) {
            super(context);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onOrientationChanged(int orientation) {
            // TODO Auto-generated method stub
            if(orientation == OrientationEventListener.ORIENTATION_UNKNOWN){
                return;
            }
            mOrientation = ViewUtil.roundOrientation(orientation, mOrientation);
            rotate =mOrientation;
                    image.setOrientation(mOrientation, true);
            textView.setRotation(-mOrientation);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // TODO Auto-generated method stub
        super.onConfigurationChanged(newConfig);
        int degree = newConfig.orientation;
        Log.i("yan", "onConfigurationChanged = " + degree);
    }
    private Handler mHandler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            switch (msg.what) {
                case WHAT_TAKE_PHOTO_SUCCEED:
                    if (msg.obj != null) {
                        Uri uri = (Uri) msg.obj;
                        Logger.d(uri);
                        if (uri != null) {
                            Glide.with(AppraiserApplication.getInstances()).load(uri).dontAnimate().fitCenter().into(image);
                                photoList.add(new TakePhotoBean(sourceID,String.valueOf(uri)));
                                sourceID++;
                            if (sourceID < photoBeanList.size()-1) {
                                    textView.setText(photoBeanList.get(sourceID).getPhotoName());
                            }else {
                                Intent intent = new Intent();
                                intent.putExtra("photoBeanList",(Serializable)photoList);
                                setResult(BACK_PHOTO_SUCCEED,intent);
                                finish();
                            }
                        }
//                        startActivity(intent);
                        // 一定要finish()，这样才会走onDestroy()方法，把Camera释放掉，否则从预览页返回或重拍会出现黑屏的情况
//                        finish();
                    }
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    protected void onResume() {
        super.onResume();
        mOrientationListener.enable();
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 解决三星S6等部分机型的黑屏问题
                try {
                    SurfaceHolder holder = vSurfaceView.getSurfaceHolder();
                    while (!holder.getSurface().isValid()) {
                        Thread.sleep(50);
                    }
                    CameraInterface.getInstance().doStartPreview(TakePhoto.this,holder,
                            DisplayUtil.getScreenWidth(TakePhoto.this), DisplayUtil.getScreenHeight(TakePhoto.this)*3/4);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    protected void onPause() {
        super.onPause();
        SurfaceHolder holder = vSurfaceView.getSurfaceHolder();
        vSurfaceView.surfaceDestroyed(holder);
        mOrientationListener.disable();
    }
    
    /**
     * 获取权限
     */
    private void getPermissions() {
        if (Build.VERSION.SDK_INT >= M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager
                    .PERMISSION_GRANTED &&
//                    ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager
//                            .PERMISSION_GRANTED &&
            ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager
                            .PERMISSION_GRANTED) {
                //具有权限
                granted = true;
                openThread.start();
            } else {
                //不有获取权限，需要进行权限申请
                ActivityCompat.requestPermissions(TakePhoto.this, new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.CAMERA}, GET_PERMISSION_REQUEST);
                granted = false;
            }
        }else{
            openThread.start();
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == GET_PERMISSION_REQUEST) {
            int size = 0;
            if (grantResults.length >= 1) {
                    int writeResult = grantResults[0];
                    //读写内存权限
                    boolean writeGranted = writeResult == PackageManager.PERMISSION_GRANTED;//读写内存权限
                    if (!writeGranted) {
                        size++;
                    }
//                //录音权限
//                int recordPermissionResult = grantResults[1];
//                boolean recordPermissionGranted = recordPermissionResult == PackageManager.PERMISSION_GRANTED;
//                if (!recordPermissionGranted) {
//                    size++;
//                }
                //相机权限
                int cameraPermissionResult = grantResults[0];// grantResults[2]
                boolean cameraPermissionGranted = cameraPermissionResult == PackageManager.PERMISSION_GRANTED;
                if (!cameraPermissionGranted) {
                    size++;
                }
                if (size == 0) {
                    granted = true;
                    openThread.start();
                } else {
                    Toast.makeText(this, "请到设置-权限管理中开启", Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }
    }
    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("photoBeanList",(Serializable)photoList);
        setResult(BACK_PHOTO_SUCCEED,intent);
        super.onBackPressed();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        CameraInterface.getInstance().doDestroyedCamera();
    }

}
